import path from 'path'

export default function analyzeBundleSizePlugin({ threshold = 1024 * 100 } = {}) {
  // 设置默认阈值为 100KB
  return {
    name: 'vite-plugin-analyze-bundle-size',
    enforce: 'post',

    generateBundle(_, bundle) {
      const modules = {}

      // 遍历所有 chunk
      for (const fileName in bundle) {
        const chunk = bundle[fileName]

        // 统计每个模块的大小
        if (chunk.type === 'chunk' && chunk.modules) {
          for (const moduleId in chunk.modules) {
            const moduleInfo = chunk.modules[moduleId]
            const moduleSize = moduleInfo.renderedLength || 0

            if (moduleId in modules) {
              modules[moduleId].size += moduleSize
            } else {
              modules[moduleId] = {
                size: moduleSize,
                fileName: path.relative(process.cwd(), moduleId)
              }
            }
          }
        }
      }

      // 找出体积过大的模块
      const largeModules = Object.values(modules).filter(module => module.size > threshold)

      // 输出警告信息
      if (largeModules.length > 0) {
        console.warn('\n⚠️  Large modules found:')
        largeModules.forEach(module => {
          console.warn(`  - ${module.fileName}: ${formatSize(module.size)}`)
        })
        console.warn('\nConsider optimizing these modules to reduce bundle size.')
      }
    }
  }
}

function formatSize(size) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let i = 0
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024
    i++
  }
  return `${size.toFixed(2)} ${units[i]}`
}
